package com.shunhao.network.newnet

import com.google.gson.JsonParseException
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

class NewApiException(
    val code: Int,
    override val message: String?,
    override val cause: Throwable? = null
) : RuntimeException(message, cause) {

    companion object {
        // 网络状态码
        const val REQUEST_OK = 200

        private const val CODE_NET_ERROR = 404

        private const val CODE_TIMEOUT = 4080

        private const val CODE_JSON_PARSE_ERROR = 4010

        private const val CODE_SERVER_ERROR = 201

        // 业务状态码
        const val CODE_AUTH_INVALID = 401

        fun build(e: Throwable): NewApiException {
            return when (e) {
                is HttpException -> {
                    NewApiException(CODE_NET_ERROR, "网络异常(${e.code()},${e.message()})")
                }
                is UnknownHostException -> {
                    NewApiException(CODE_NET_ERROR, "网络连接失败，请检查后再试")
                }
                is ConnectTimeoutException, is SocketTimeoutException -> {
                    NewApiException(CODE_TIMEOUT, "请求超时，请稍后再试")
                }
                is IOException -> {
                    NewApiException(CODE_NET_ERROR, "网络异常(${e.message})")
                }
                is JsonParseException, is JSONException -> {
                    // Json解析失败
                    NewApiException(CODE_JSON_PARSE_ERROR, "数据解析错误，请稍后再试")
                }
                else -> {
                    NewApiException(CODE_SERVER_ERROR, "系统错误(${e.message})")
                }
            }
        }
    }

    fun <T> toResponse(): ResponseResult<T> {
        return ResponseResult(code, message)
    }
}
